package com.tree.redisson.runner;

import cn.hutool.json.JSONUtil;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.tree.redisson.IUserService;
import com.tree.redisson.entity.User;
import com.tree.redisson.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName com.tree.redisson.runner
 * Description: <类功能描述>.
 * <br>
 * @Author frankzsliu
 * @Date 2020/11/8 10:29 下午
 * @Version 1.0
 */
@Slf4j
@Component
public class LoadPlanProducerThread extends Thread{

    /**
     * master exec service
     */
    private ExecutorService loadPlanExecutor = Executors.newFixedThreadPool(
    10,
            new ThreadFactoryBuilder().setDaemon(true)
                        .setNameFormat("LoadPlan-producer-Thread")
                        .build());

    private List<User> userList;

    @PostConstruct
    public void init(){
        initProduceUser();
    }

    private void initProduceUser() {
        List<User> userList = new ArrayList<>();
        for(int i =0; i< 5; i++){
            userList.add(new User(getIncr(),"tree", -1));
        }
        userService.saveBatch(userList);
        log.info("初始化5个用户， 详情为"+JSONUtil.toJsonPrettyStr(userService.list()));

    }

    @Autowired
    private IUserService userService;
    @Autowired
    private RedisService redisService;

    @Override
    public void run() {
        Random rand = new Random();
        while (true) {
            int sleepTime = rand.nextInt(10);
            //indicate that no command ,sleep for 1s

            User user = new User(getIncr(), "tree",-1 );
            log.info("开始生产用户【"+Thread.currentThread()+"】： 增加一个未激活用户 "+ JSONUtil.toJsonPrettyStr(user));
            userService.save(user);
            log.info("完成生产用户 【"+Thread.currentThread()+"】， 休息[" + sleepTime + "]秒... ");
            try {
                Thread.sleep(sleepTime * 1000);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }
        }
    }

    public int getIncr(){
        String key = "order:incr:";
        int incrNo = (int) redisService.incr(key, (long) 1);
        return incrNo;
    }
}
